import { reqGoodsList } from '@/api';



const state = {
  goodsList: [],//模拟数据请求
};
const getters = {  
  foodList(state){
    let arr=[]
    state.goodsList&&state.goodsList.forEach(item => {
      item.foods.forEach((item) =>{
        if(item.count>0){
          arr.push(item)
        }
      })
    })
    return arr
  },
  foodsNum(state){
    let num = 0
    state.goodsList&&state.goodsList.forEach(item => {
      item.foods.forEach((item) =>{
        if(item.count>0){
          num += item.count
        }
      })
    })
    return num
  },
  foodPrice(state){
    let price = 0
    state.goodsList&&state.goodsList.forEach(item => {
      item.foods.forEach((item) =>{
        if(item.count>0){
          price += item.count*item.price
        }
      })
    })
    return price
  },
  

};
const mutations = {
  RECEIVEGOODSLIST(state, goodsList) {
    state.goodsList = goodsList
  },
  foodsnum(state,{foodsnum,index,a}){
    state.goodsList[index].foods.forEach(v=>{
      if(v.name === foodsnum&&a===1)  {
        v.count++
      }
      if(v.name === foodsnum&&a===0){
        v.count--
        if(v.count <= 1){
          v.count = 0
        }
      }
    })
  },
  clearCart(state) {
    console.log(111111);
    state.goodsList&&state.goodsList.forEach(item => {
      item.foods.forEach((item) =>{
        if(item.count>0){
          item.count=0
        }
      })
    })
  }
};
const actions = {
  async getGoodsList({ commit }, payload) {
    const result = await reqGoodsList();
    result.data.forEach((item,index)=>{
      item.id = index
      item.foods.forEach(item => {
        item.idx = index
        item.count = 0
      })
    })
    console.log(result.data);
    if (result.code === 200) {
      commit('RECEIVEGOODSLIST', result.data);
    }
  },
};

export default {
  state,
  getters,
  mutations,
  actions,
};
